#include <iostream>
using namespace std;

struct TreeLinkNode {
    int val;
    TreeLinkNode *right;
    TreeLinkNode *left;
    TreeLinkNode *next;
    TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
};

class Solution {
public:
    void connect(TreeLinkNode *root) {
        TreeLinkNode *p;
        while (root != NULL) {
            p = root;
            while (p != NULL) {
                if (p->left != NULL) {
                    p->left->next = p->right;
                    if (p->next != NULL) {
                        p->right->next = p->next->left;
                    }
                }
                p = p->next;
            }
            root = root->left;
        }
    }
};
